//
//  MineVC.swift
//  JTYP
//
//  Created by Groot on 2017/12/8.
//  Copyright © 2017年 inspur. All rights reserved.
//

//private let kNavBarBottom = WRNavigationBar.navBarBottom()
//private let IMAGE_HEIGHT:CGFloat = 200
//private let NAVBAR_COLORCHANGE_POINT:CGFloat = IMAGE_HEIGHT - CGFloat(kNavBarBottom * 2)

class MineVC: TransparentNavBarVC {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var kHeaderHeight: CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if isSmallIphone() {
            kHeaderHeight = 180
        }else {
            kHeaderHeight = 210
        }
        
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never;
        }else {
            self.automaticallyAdjustsScrollViewInsets = false;
        }
        
//        let v = UIView.init(frame: self.view.bounds)
//        v.backgroundColor = .red
//        //collectionView.backgroundView = v
        
        let kScreenWidth = UIScreen.main.bounds.width
        let collectionLayout = CustomCollectionViewFlowLayout()
        collectionLayout.minimumLineSpacing = 0
        collectionLayout.minimumInteritemSpacing = 0
        collectionLayout.headerReferenceSize = CGSize.init(width: kScreenWidth, height: kHeaderHeight)
        collectionLayout.footerReferenceSize = .zero
        
        collectionView.setCollectionViewLayout(collectionLayout, animated: true)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        
        /// CELL
        collectionView.register(UINib.init(nibName: "UserInfoHeaderCell", bundle: nil), forCellWithReuseIdentifier: UserInfoHeaderCell.CellIdentifier)
        collectionView.register(UINib.init(nibName: "UserFuncCell", bundle: nil), forCellWithReuseIdentifier: UserFuncCell.CellIdentifier)
        
        /// HEADER & FOOTER
        collectionView.register(UINib.init(nibName: "UserInfoHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: UserInfoHeaderView.CellIdentifier)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        // refresh control
        // Refresh Header & Footer
//        let header = ALoadingHeader.init(refreshingTarget: self, refreshingAction: #selector(reload))
//        //        header?.setTitle(APPName, for: .idle)
//        //        header?.arrowView.isHidden = true
//        //        header?.stateLabel.textColor = UIColor.init(white: 0.5, alpha: 1)
//        //        header?.lastUpdatedTimeLabel.isHidden = true
//        collectionView.mj_header = header
        collectionView.bounces = true
        collectionView.alwaysBounceVertical = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(userInfoChanged), name: NSNotification.Name(rawValue: CUserManager.KUserStatusChanged), object: nil)
    }
    
    @objc func userInfoChanged() {
        collectionView.reloadItems(at: [IndexPath.init(row: 0, section: 0)])
    }
}

extension MineVC: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource  {
    // MARK: UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserInfoHeaderCell.CellIdentifier, for: indexPath) as! UserInfoHeaderCell
            cell.setData(userInfo: CUserManager.shareInstance.cUser)
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserFuncCell.CellIdentifier, for: indexPath) as! UserFuncCell
            return cell
        }
        
    }
    
    // MARK: UICollectionViewDelegateFlowLayout
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.width, height: kHeaderHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let reusableView: UserInfoHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: UserInfoHeaderView.CellIdentifier, for: indexPath) as! UserInfoHeaderView
        reusableView.setData(userInfo: CUserManager.shareInstance.cUser)

        return reusableView
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.row == 0 {
            if isSmallIphone() {
                return CGSize.init(width: collectionView.frame.size.width, height: 125)
            }else {
                return CGSize.init(width: collectionView.frame.size.width, height: 150)
            }
        }else {
            if isSmallIphone() {
                return CGSize.init(width: collectionView.frame.size.width, height: 225)
            }else {
                return CGSize.init(width: collectionView.frame.size.width, height: 250)
            }
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
}

class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let collectionView = self.collectionView
        let insets = collectionView?.contentInset
        let offset = collectionView?.contentOffset
        let minY = -((insets?.top)!)
        
        let attributesArray = super.layoutAttributesForElements(in: rect)
        if offset!.y < minY {
            let headerSize = self.headerReferenceSize
            let deltaY = CGFloat(fabsf(Float((offset?.y)! - CGFloat(minY))))
            
            for attrs:UICollectionViewLayoutAttributes in attributesArray! {
                
                if attrs.representedElementKind == UICollectionElementKindSectionHeader {
                    var headerRect = attrs.frame
                    headerRect.size.height = max(minY, headerSize.height + deltaY)
                    headerRect.origin.y = headerRect.origin.y - deltaY
                    attrs.frame = headerRect
                    break
                }
            }
        }
        
        return attributesArray
    }
}
